<template>
  <div class="container-fluid novelcontainer">
    <div class="row random">
      随机推荐
    </div>
    <div v-for="novel in novels" :key="novel.novel_id" class="row g-0 novellist" @click="goToNovel(novel.novel_id)">
        <div class="col-4"><img :src="novel.novel_pic" alt="小说封面" class="novel-image" /></div>
        <div class="col novel_list_info">
          <div class="row novel_name">{{ truncate2(novel.novel_name) }}</div>
          <div class="row novel_author">作者：{{ novel.novel_author.nickname }}</div>
          <div class="row">简介：{{ truncate(novel.novel_desc) }}</div>
        </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router'; // 引用 Vue Router
import axios from 'axios';
import config from "../../../config/config.js";

const novels = ref([]);
const router = useRouter(); // 获取路由实例
// 跳转到指定小说的函数
const goToNovel = (novelId) => {
  router.push(`/novel/${novelId}`); // 路由跳转
};

const fetchNovels = async () => {
  try {
    const response = await axios.get(`${config.apiUrl}/novel/random`);
    novels.value = response.data;
  } catch (error) {
    console.error("Failed to fetch novels:", error);
  }
};

const truncate = (text) => {
  if (!text) return '';
  return text.length > 40 ? text.substring(0, 30) + '...' : text;
};
const truncate2 = (text) => {
  if (!text) return '';
  return text.length > 12 ? text.substring(0, 12) + '...' : text;
};

onMounted(fetchNovels);
</script>

<style scoped>
.random{
  padding:10px 20px 0px 20px;
  font-weight: bold;
  font-size: 22px;
  letter-spacing: 2px;
}
.novellist{
  padding: 10px;
  cursor: pointer;
}
.novelcontainer{
  border-radius: 20px;
  width: 90%;
  padding: 10px;
  box-shadow:0px 0px 80px rgba(0, 0, 0, 0.06);
  margin-top: 10px;
}
.novellist img{
  width: 100px;
}
.novel_list_info{
  padding-left: 20px;
}
.novel_name{
  font-size: 17px;
  font-weight: bold;
}
.novel_author{
  padding: 4px 0px;
}
.novel-image{
  width: 135px;
  height: 138px;
}

</style>
